package org.hepeng.workx.jdbc;

import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.hepeng.workx.exception.ApplicationRuntimeException;
import org.hepeng.workx.extension.DefaultXImpl;

import javax.sql.DataSource;
import java.util.Objects;

/**
 * @author he peng
 */

@DefaultXImpl
public class DataSourceRouteAnnotationSelectDataSourceStrategy extends RandomReadAndWriteModeSelectDataSourceStrategy {

    @Override
    public DataSource chooseDataSource(Object key) {
        DataSourceRoute dataSourceRoute =
                DataSourceRouteContext.getContext().getDataSourceRoute();

        if (Objects.isNull(dataSourceRoute) || dataSourceRoute.value().length == 0) {
            return super.chooseDataSource(key);
        }

        String[] datasourceIds = dataSourceRoute.value();
        String datasourceId = datasourceIds[RandomUtils.nextInt(0, datasourceIds.length)];
        DataSource ds = null;
        for (DataSourceMetadata dsInfo : getAllDataSources()) {
            if (StringUtils.equals(dsInfo.getId() , datasourceId)) {
                ds = dsInfo.getDataSource();
                break;
            }
        }

        if (Objects.isNull(ds)) {
            throw new ApplicationRuntimeException("No data source was found for the specified id [" + datasourceId + "]");
        }
        return ds;
    }
}
